//
//  RoundIndicator.swift
//  
//
//  Created by 孙长坦 on 2022/7/21.
//

import Foundation
import UIKit
import QuartzCore

public class RoundIndicator: CALayer, IndicatorProtocol {
    public var indicatorHeight: CGFloat = 26
    public var padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 11)
    
    public override init(layer: Any) {
        super.init(layer: layer)
    }
    
    public override init() {
        super.init()
        
        masksToBounds = true
        cornerRadius = 13
        
        backgroundColor = Theme.shared.currentThemeData.topTabBarIndicatorColor.cgColor
        
        bounds = CGRect(x: 0, y: 0,
                        width: 0, height: indicatorHeight)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func set(frame: CGRect, animated: Bool) {
        CATransaction.begin()
        CATransaction.setDisableActions(!animated)
        
        self.frame = frame.insetBy(dx: 0, dy: (frame.height - indicatorHeight) / 2)
        
        CATransaction.commit()
    }
    
    public func moveTo(item: UIView, animated: Bool) -> CGRect {
        var itemSize = item.sizeThatFits(CGSize(width: UIView.noIntrinsicMetric,
                                                height: UIView.noIntrinsicMetric))
        itemSize.width += padding.left + padding.right
        
        let itemFrame = item.frame
        
        let indicatorFrame = itemFrame.insetBy(dx: (itemFrame.width - itemSize.width) / 2, dy: 0)
        set(frame: indicatorFrame, animated: animated)
        
        return indicatorFrame
    }
    
    public func onMove(fromItem: UIView, toItem: UIView, movePrecent: CGFloat) -> CGRect {
        let paddingWidth = padding.left + padding.right
        
        var fromSize = fromItem.sizeThatFits(CGSize(width: UIView.noIntrinsicMetric,
                                                    height: UIView.noIntrinsicMetric))
        fromSize.width += paddingWidth
        
        var toSize = toItem.sizeThatFits(CGSize(width: UIView.noIntrinsicMetric,
                                                height: UIView.noIntrinsicMetric))
        toSize.width += paddingWidth
        
        let fromFrame = fromItem.frame.insetBy(dx: (fromItem.frame.width - fromSize.width) / 2, dy: 0)
        let toFrame = toItem.frame.insetBy(dx: (toItem.frame.width - toSize.width) / 2, dy: 0)
        let start = fromFrame.midX
        let end = toFrame.midX
        
        let dx = (toFrame.width - fromFrame.width) * abs(movePrecent) / 2
        let midX = start + abs(end - start) * movePrecent
        
        var indicatorFrame = fromFrame.insetBy(dx: -dx, dy: 0)
        indicatorFrame.origin.x = midX - indicatorFrame.width / 2
        
        set(frame: indicatorFrame, animated: false)
        
        return indicatorFrame
    }
}
